/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.unicamp.ic.sgct.persistencia.test;

import java.io.File;
import java.io.FileInputStream;
import java.sql.SQLException;
import org.dbunit.IDatabaseTester;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.operation.DatabaseOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author arthur
 */
public class LoaderData {

    protected static final Log LOGGER = LogFactory.getLog(LoaderData.class);
    
    private static IDatabaseTester databaseTester = null;

    private SituacaoServidor situacaoServidor;
    enum SituacaoServidor{
        PARADO, INICIANDO;
    }



    public LoaderData() {
        
    }

    
    public static void exec(String nome) throws Exception {
        

        if(databaseTester == null){
            databaseTester = new JdbcDatabaseTester("org.hsqldb.jdbcDriver","jdbc:hsqldb:hsql://127.0.0.1", "sa", "");
        }
        
        IDatabaseConnection connection = null;
        IDataSet dataSet = null;
        try {
            connection = databaseTester.getConnection();
            dataSet = getDataSet(nome);
            LOGGER.info("APAGANDO DADOS DA BASE DE DADOS");
            DatabaseOperation.DELETE_ALL.execute(connection, dataSet);
            LOGGER.info("DADOS DA BASE APAGADOS");
            LOGGER.info("CARREGANDO DADOS DE TESTE NA BASE DE DADOS");
            DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet);
            LOGGER.info("DADOS DE TESTE CARREGADOS NA BASE DE DADOS");
        } catch(Exception ex){
            LOGGER.error("ERRO CARREGAMENTO DE DADOS", ex);
            throw ex;
        }finally{
            try {
                if(connection != null){
                    connection.close();
                }
            } catch (SQLException ex) {
                LOGGER.error(ex);
            }
        }
        LOGGER.info("DADOS DE TESTE CARREGADOS");
    }

    

     protected static IDataSet getDataSet(String nome) throws Exception
    {
         File file = new File(nome);
         if(file.exists()){
            return new FlatXmlDataSet(new FileInputStream(nome));
         }else{
            throw new RuntimeException("O arquivo " + nome + " nao existe");
         }
        
    }


    

}
